<template>
  <div class="login">
    <div class="login-con">
      <!-- 顶部切换 -->
      <ul class="menu-tab">
        <li v-for="item in menuData" :key="item.type" :class="{ current: item.current }" @click="clickMenu(item)">
          {{ item.txt }}
        </li>
      </ul>
      <!-- 表单部分 -->
      <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="80px" class="demo-ruleForm">

        <el-form-item prop="username" class="item-from">
          <label for="username">用户名</label>
          <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="email" class="item-from" v-show="model === 'register'">
          <label for="email">邮箱</label>
          <el-input v-model="ruleForm.email" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="password" class="item-from">
          <label for="password">密码</label>
          <el-input id="password" type="password" v-model="ruleForm.password" autocomplete="off" minlength="6"
            maxlength="20"></el-input>
        </el-form-item>

        <el-form-item prop="repassword" class="item-from" v-show="model === 'register'">
          <label>确认密码</label>
          <el-input type="password" v-model="ruleForm.repassword" autocomplete="off" minlength="6"
            maxlength="20"></el-input>
        </el-form-item>

        <el-form-item class="btn">
          <!-- 登录、注册按钮 -->
          <el-button type="danger" class="login-btn block" @click="submitForm(ruleFormRef)" :disabled="btnbool">{{ model
            === 'login' ? "登录" :
            "注册" }}</el-button>
          <!-- 重置按钮 -->
          <el-button type="info" @click="resetForm(ruleFormRef)" style="margin-left: 50px">重置</el-button>
        </el-form-item>

      </el-form>
    </div>
  </div>
</template>
  
<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from "vue";
// 引入饿了么UI需要的
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from "element-plus";
// 引入封装的表单验证方法
import * as verification from "../util/verification"
// 导入封装好的axios
import link from "../api/apis";
// 引入MD5加密
import { Md5 } from 'ts-md5';
// 导入路由vue-router
import { useRouter } from "vue-router";
// 引用useStore
import { useStore } from "vuex";
// 得到store对象
const store = useStore();
// 定义MD5对象
const md5: any = new Md5()
let router = useRouter()

// 表单数据
const ruleForm = reactive({
  age: '',
  username: '',
  password: '',
  repassword: '',
  email: ''
})
// tab切换数据
const menuData = reactive([
  {
    txt: "登录",
    current: true,
    type: "login"

  },
  {
    txt: "注册",
    current: false,
    type: "register"
  }
])
const model = ref('login')
// 切换模块
const clickMenu = (data: any) => {
  //先让所有的数据都变成false没有选中状态
  menuData.forEach((elem) => {
    // 清空input框的值
    ruleForm.username = '';
    ruleForm.password = '';
    ruleForm.repassword = '';
    ruleForm.email = '';
    elem.current = false;
  });
  // 在让点击的那个变成选中状态
  data.current = true;
  // 修改模块值
  model.value = data.type;
};
// 创建一个变量用来控制按钮是否能点击
let btnbool = ref(true)

// 自定义确认密码规则
const checkRepass = (rule: any, value: any, callback: any) => {
  // 登录时没有验证重复密码
  if (model.value === 'login') { callback(); }
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== ruleForm.password) {
    callback(new Error("两次密码输入不一致!"))
  } else {
    callback()
  }
}
// 验证用户名
const checkName = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入用户名'))
  } else if (verification.checkName(value)) {
    callback(new Error("用户名必须由字母、数字组成,长度为8-18位"))
  } else {
    callback()
  }
}
// 验证密码
const checkPass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (verification.checkPass(value)) {
    callback(new Error("请输入4到16位（字母，数字，下划线，减号）密码"))
  } else {
    callback()
  }
}
// 验证邮箱
const checkEmail = (rule: any, value: any, callback: any) => {
  // 登录时没有验证邮箱
  if (model.value === 'login') { callback(); }
  if (value === '') {
    callback(new Error('请输入邮箱！'))
  } else if (verification.checkEmail(value)) {
    callback(new Error('请输入正确格式的邮箱！'))
  } else {
    callback()
  }
}


// 验证规则
const rules = reactive<FormRules>({
  username: [{ validator: checkName, trigger: 'blur' }],
  email: [{ validator: checkEmail, trigger: 'blur' }],
  repassword: [{ validator: checkRepass, trigger: 'blur' }],
  password: [{ validator: checkPass, trigger: 'blur' }],

})

const ruleFormRef = ref<FormInstance>()

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!')
      // 判断是登录还是注册
      // 发送请求
      if (model.value == 'login') {
        console.log('登录');
        link(`/register?name=${ruleForm.username}&password=${md5.appendAsciiStr(ruleForm.password)}`, "GET").then((ok) => {
          // console.log(333,ok);
          let { data } = ok;//解构出数据
          // 判断data长度不为0登录成功
          console.log(data);

          if (data.length != 0) {
            console.log("登录成功")
            let obj = {
              id: data[0].id,
              username: data[0].name,
              power: data[0].power
            }
            console.log('obj', obj);

            // 触发 store 保存 token
            store.dispatch('updateToken', JSON.stringify(obj))
            // 登陆成功跳转到首页
            router.push("/home")
          } else {
            console.log("登录失败")
          }
        })
      } else {
        // 把要发送的数据拼装成一个对象
        let data = {
          'name': ruleForm.username,
          'password': md5.appendAsciiStr(ruleForm.password),
          "email": ruleForm.email,
          "power": []
        }
        console.log(333, data);

        link("/register", "POST", data).then((ok) => {
          // console.log(ok, 1111);
          // 判断数据是否为空 不为空表示注册成功
          let { data } = ok
          // 转成成数组判断长度即可知道对象是否为空
          if (Object.keys(data).length !== 0) {
            ElMessage({
              message: '注册成功',
              type: 'success',
              duration: 1000
            })
            // 注册成功切换到登录
            model.value = "login"
            menuData.forEach((elem) => {
              elem.current = false;
            });
            menuData[0].current = true;
          } else {
            ElMessage({
              message: '注册失败',
              type: 'error',
              duration: 1000
            })
          }
        })
      }

    } else {
      console.log('error submit!')
      return false
    }
  })
}
// 重置输入框
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// onMounted(() => {
//   console.log(process.env.VUE_APP_API);
// })
// 监听输入框来控制按钮是否可点击
watch(ruleForm, (newval) => {
  // console.log(newval);
  // 登录时
  if (model.value == 'login') {
    // 当用户名和密码不为空时才允许点击按钮
    if (newval.username != "" && newval.password != "") {
      btnbool.value = false
    } else {
      btnbool.value = true
    }
  } else {
    // 注册
    if (newval.username != "" && newval.password != "" && newval.repassword != "" && newval.email != "") {
      btnbool.value = false
    } else {
      btnbool.value = true
    }
  }

})
</script>
  

<style lang="scss" scoped>
.login {
  padding-top: 20px;
  background: linear-gradient(35deg, #8499de, #FFCCCC);
  height: 100%;
}

html,
body,
#app {
  //设置页面100%高
  height: 100%;
}

// 设置切换样式开始
.login-wrap {
  width: 330px;
  margin: auto;
}

.menu-tab {
  text-align: center;

  li {
    display: inline-block;
    width: 88px;
    line-height: 36px;
    font-size: 14px;
    color: #fff;
    border-radius: 2px;
    cursor: pointer;
  }

  .current {
    background-color: rgba(255, 255, 255, 0.5); //白色半透明
  }

}

.demo-ruleForm {
  width: 400px;
  margin: 0 auto;
  padding-right: 30px;
}
</style>
